<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="时间范围">
                    <el-date-picker v-model="searchForm.timeRange" type="datetimerange" range-separator="至"
                        start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>

                <el-form-item label="监测量">
                    <el-select v-model="searchForm.monitorCodes" placeholder="请选择监测量" multiple clearable @change="handleSearch"
                        style="width: 300px;">
                        <el-option v-for="item in monitoringOptions" :key="item.monitorCode" :label="item.monitorName"
                            :value="item.monitorCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 300px;">
                        <el-option label="草稿" :value="0" />
                        <el-option label="提交" :value="1" />
                        <el-option label="已审核" :value="2" />
                        <el-option label="已驳回" :value="9" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="success" @click="handleAdd">新增数据</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="table-card">
            <div class="table-header">
                <span>数据填报列表</span>
                <div>
                    <el-button type="success" size="small" @click="handleBatchApprove"
                        :disabled="selectedRows.length === 0">
                        批量审核
                    </el-button>
                    <el-button type="danger" size="small" @click="handleBatchReject"
                        :disabled="selectedRows.length === 0">
                        批量驳回
                    </el-button>
                </div>
            </div>

            <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" border stripe>
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="monitorCode" label="监测量编码" align="center" />
                <el-table-column prop="monitorName" label="监测量名称" align="center" />
                <el-table-column prop="ts" label="数据时间" align="center">
                    <template #default="{ row }">
                        {{ formatDateTime(row.ts) }}
                    </template>
                </el-table-column>
                <el-table-column prop="val" label="上报值" align="center" width="100">
                    <template #default="{ row }">
                        {{ row.val?.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" align="center" width="80" />
                <el-table-column prop="status" label="状态" align="center" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="overrideFlag" label="覆盖设备数据" align="center" width="120">
                    <template #default="{ row }">
                        <el-tag :type="row.overrideFlag === 1 ? 'success' : 'info'">
                            {{ row.overrideFlag === 1 ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="submitUser" label="提交人" align="center" width="100" />
                <el-table-column prop="approveUser" label="审核人" align="center" width="100" />
                <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
                <el-table-column label="操作" align="center" width="200" fixed="right">
                    <template #default="{ row }">
                        <!-- <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button> -->
                        <el-button type="text" size="small" @click="handleView(row)">查看</el-button>
                        <el-button type="text" size="small" @click="handleSubmit(row)" v-if="row.status === 0">
                            提交
                        </el-button>
                        <el-button type="text" size="small" @click="handleApprove(row)" v-if="row.status === 1">
                            审核
                        </el-button>
                        <el-button type="text" size="small" @click="handleReject(row)" v-if="row.status === 1">
                            驳回
                        </el-button>
                        <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination class="mt-2" v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize" :total="pagination.total" :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>

        <!-- 趋势图表 -->
        <el-card class="chart-card mt-2">
            <div class="chart-header">
                <el-row>
                    <el-col :span="12">
                        <el-select v-model="chartTimeDimension" placeholder="时间维度"  @change="loadChartData">
                            <el-option label="日" :value="1" />
                            <el-option label="月" :value="2" />
                            <el-option label="年" :value="3" />
                        </el-select>

                    </el-col>
                    <el-col :span="12" style="">
                        <el-date-picker style="margin-left: 20px;" v-model="chartTime" :type="getChartDatePickerType()" placeholder="选择时间"
                            value-format="YYYY-MM-DD" class="ml-2" @change="loadChartData" />
                    </el-col>
                </el-row>
            </div>
            <Echarts :option="chartOption" height="400px" />
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
                <el-form-item label="监测量" prop="monitorCode" >
                    <el-select v-model="formData.monitorCode" @change="targetMonitorCode" placeholder="请选择监测量" style="width: 100%">
                        <el-option v-for="item in monitoringOptions" :key="item.monitorCode" :label="item.monitorName"
                            :value="item.monitorCode" />
                    </el-select>
                </el-form-item>

                <el-form-item label="数据时间" prop="ts">
                    <el-date-picker v-model="formData.ts" type="datetime" placeholder="选择数据时间"
                        value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </el-form-item>

                <el-form-item label="上报值" prop="val">
                    <el-input-number v-model="formData.val" :precision="2" :step="0.1" controls-position="right"
                        style="width: 100%" />
                </el-form-item>

                <el-form-item label="单位">
                    <el-input v-model="formData.unit" placeholder="请输入单位" />
                </el-form-item>

                <el-form-item label="覆盖设备数据">
                    <el-switch v-model="formData.overrideFlag" :active-value="1" :inactive-value="0" />
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="数据详情" width="600px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="监测量编码">{{ detailData.monitorCode }}</el-descriptions-item>
                <el-descriptions-item label="监测量名称">{{ detailData.monitorName }}</el-descriptions-item>
                <el-descriptions-item label="数据时间">{{ formatDateTime(detailData.ts) }}</el-descriptions-item>
                <el-descriptions-item label="上报值">{{ detailData.val?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getStatusType(detailData.status)">
                        {{ getStatusText(detailData.status) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="覆盖设备数据">
                    <el-tag :type="detailData.overrideFlag === 1 ? 'success' : 'info'">
                        {{ detailData.overrideFlag === 1 ? '是' : '否' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="提交人">{{ detailData.submitUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审核人">{{ detailData.approveUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDateTime(detailData.updateTime) }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <el-button @click="detailDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Echarts from '@/components/ECharts'
import dayjs from 'dayjs'

import {
    getRawList,
    getMonitoringList,
    batchUpsert,
    batchStatus,
    getTrendData,
    exportRawData
} from '@/api/dispatch/analyze/data_reporting'

// 搜索表单
const searchForm = reactive({
    timeRange: [],
    monitorCodes: [],
    plantId: '',
    siteId: '',
    status: ''
})

// 分页参数
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 图表参数
const chartTimeDimension = ref(1)
const chartTime = ref(dayjs().format('YYYY-MM-DD'))

// 数据列表
const monitoringOptions = ref([])
const tableData = ref([])
const selectedRows = ref([])
const trendData = ref([])

// 对话框控制
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('新增数据')
const formRef = ref(null)

// 表单数据
const formData = reactive({
    monitorCode: '',
    ts: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    val: 0,
    plantId: '',
    siteId: '',
    unit: '',
    overrideFlag: 0,
    remark: ''
})


const targetMonitorCode = (e) => {
    const item = monitoringOptions.value.find(item => item.monitorCode == e)
    formData.unit = item?.monitorUnit;

    
}

// 详情数据
const detailData = reactive({})

// 加载状态
const loading = ref(false)

// 表单验证规则
const formRules = {
    monitorCode: [
        { required: true, message: '请选择监测量', trigger: 'change' }
    ],
    ts: [
        { required: true, message: '请选择数据时间', trigger: 'change' }
    ],
    val: [
        { required: true, message: '请输入上报值', trigger: 'blur' }
    ]
}

// 初始化数据
onMounted(() => {
    fetchMonitoringList()
    fetchTableData()
    loadChartData()
})

// 获取监测量列表
const fetchMonitoringList = async () => {
    try {
        const res = await getMonitoringList()
        monitoringOptions.value = res.data || []
    } catch (error) {
        console.error('获取监测量列表失败:', error)
        ElMessage.error('获取监测量列表失败')
    }
}

// 获取表格数据
const fetchTableData = async () => {
    try {
        loading.value = true
        const params = {
            ...searchForm,
            start: searchForm.timeRange?.[0] || '',
            end: searchForm.timeRange?.[1] || '',
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize
        }

        const res = await getRawList(params)
        tableData.value = res?.rows || []
        pagination.total = res?.total || 0
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

// 加载图表数据
const loadChartData = async () => {
    try {
        if (!searchForm.monitorCodes || searchForm.monitorCodes.length === 0) {
            return
        }

        const params = {
            timeDimension: chartTimeDimension.value,
            time: chartTime.value,
            monitorCodes: searchForm.monitorCodes.join(',')
        }

        const res = await getTrendData(params)
        trendData.value = res.data || []
    } catch (error) {
        console.error('获取图表数据失败:', error)
        ElMessage.error('获取图表数据失败')
    }
}

// 处理查询
const handleSearch = () => {
    pagination.currentPage = 1
    fetchTableData()
    loadChartData()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        timeRange: [],
        monitorCodes: [],
        plantId: '',
        siteId: '',
        status: ''
    })
    handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size
    fetchTableData()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchTableData()
}

// 处理行选择
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 新增数据
const handleAdd = () => {
    dialogTitle.value = '新增数据'
    Object.assign(formData, {
        monitorCode: '',
        ts: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        val: 0,
        plantId: '',
        siteId: '',
        unit: '',
        overrideFlag: 0,
        remark: ''
    })
    dialogVisible.value = true
}

// 编辑数据
const handleEdit = (row) => {
    dialogTitle.value = '编辑数据'
    Object.assign(formData, {
        monitorCode: row.monitorCode,
        ts: row.ts,
        val: row.val,
        plantId: row.plantId,
        siteId: row.siteId,
        unit: row.unit,
        overrideFlag: row.overrideFlag,
        remark: row.remark
    })
    dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
    Object.assign(detailData, row)
    detailDialogVisible.value = true
}

// 保存数据
const handleSave = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()

        const submitData = [{
            monitorCode: formData.monitorCode,
            ts: formData.ts,
            val: formData.val,
            plantId: formData.plantId,
            siteId: formData.siteId,
            unit: formData.unit,
            overrideFlag: formData.overrideFlag,
            remark: formData.remark
        }]

        await batchUpsert(submitData)
        ElMessage.success('保存成功')
        dialogVisible.value = false
        fetchTableData()
    } catch (error) {
        console.error('保存失败:', error)
        if (error !== 'validate') {
            ElMessage.error('保存失败')
        }
    }
}

// 提交数据
const handleSubmit = async (row) => {
    try {
        await ElMessageBox.confirm('确认提交该数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await batchStatus({
            ids: [row.id],
            status: 1
        })
        ElMessage.success('提交成功')
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('提交失败:', error)
            ElMessage.error('提交失败')
        }
    }
}

// 审核数据
const handleApprove = async (row) => {
    try {
        await ElMessageBox.confirm('确认审核通过该数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await batchStatus({
            ids: [row.id],
            status: 2
        })
        ElMessage.success('审核成功')
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('审核失败:', error)
            ElMessage.error('审核失败')
        }
    }
}

// 驳回数据
const handleReject = async (row) => {
    try {
        await ElMessageBox.confirm('确认驳回该数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await batchStatus({
            ids: [row.id],
            status: 9
        })
        ElMessage.success('驳回成功')
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('驳回失败:', error)
            ElMessage.error('驳回失败')
        }
    }
}

// 删除数据
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('确认删除该数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 这里需要调用删除接口，暂时使用状态更新模拟
        await batchStatus({
            ids: [row.id],
            status: 9
        })
        ElMessage.success('删除成功')
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 批量提交
const handleBatchSubmit = async () => {
    try {
        await ElMessageBox.confirm(`确认提交选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const ids = selectedRows.value.map(row => row.id)
        await batchStatus({
            ids: ids.join(','),
            status: 1
        })
        ElMessage.success('批量提交成功')
        selectedRows.value = []
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量提交失败:', error)
            ElMessage.error('批量提交失败')
        }
    }
}

// 批量审核
const handleBatchApprove = async () => {
    try {
        await ElMessageBox.confirm(`确认审核通过选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const ids = selectedRows.value.map(row => row.id)
        await batchStatus({
            ids: ids,
            status: 2
        })
        ElMessage.success('批量审核成功')
        selectedRows.value = []
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量审核失败:', error)
            ElMessage.error('批量审核失败')
        }
    }
}

// 批量驳回
const handleBatchReject = async () => {
    try {
        await ElMessageBox.confirm(`确认驳回选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const ids = selectedRows.value.map(row => row.id)
        await batchStatus({
            ids: ids,
            status: 9
        })
        ElMessage.success('批量驳回成功')
        selectedRows.value = []
        fetchTableData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量驳回失败:', error)
            ElMessage.error('批量驳回失败')
        }
    }
}

// 导出数据
const handleExport = async () => {
    try {
        const params = {
            ...searchForm,
            start: searchForm.timeRange?.[0] || '',
            end: searchForm.timeRange?.[1] || ''
        }

        const res = await exportRawData(params)

        // 创建Blob对象并下载
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `数据填报_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
        link.click()
        URL.revokeObjectURL(link.href)

        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 获取状态类型
const getStatusType = (status) => {
    switch (status) {
        case 0: return 'info' // 草稿
        case 1: return 'warning' // 提交
        case 2: return 'success' // 已审核
        case 9: return 'danger' // 已驳回
        default: return 'info'
    }
}

// 获取状态文本
const getStatusText = (status) => {
    switch (status) {
        case 0: return '草稿'
        case 1: return '提交'
        case 2: return '已审核'
        case 9: return '已驳回'
        default: return '未知'
    }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-'
    return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 获取图表日期选择器类型
const getChartDatePickerType = () => {
    switch (chartTimeDimension.value) {
        case 1: return 'date'
        case 2: return 'month'
        case 3: return 'year'
        default: return 'date'
    }
}

// 图表配置
const chartOption = computed(() => {
    const series = trendData.value.map(item => ({
        name: item.label || item.metric,
        type: 'line',
        data: item.points?.map(point => point.value) || [],
        smooth: true,
        symbol: 'circle',
        symbolSize: 6
    }))

    const xAxisData = trendData.value[0]?.points?.map(point => point.date.split(' ')[1].slice(0, 2)) || []

    return {
        title: {
            text: '数据趋势分析',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: series.map(s => s.name),
            bottom: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
        },
        yAxis: {
            type: 'value'
        },
        series: series
    }
})
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 15px;
}

.table-card {
    margin-bottom: 20px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.chart-card {
    margin-bottom: 20px;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.mt-2 {
    margin-top: 20px;
}

.ml-2 {
    margin-left: 10px;
}

:deep(.el-table) {
    margin-top: 0;
}

:deep(.el-pagination) {
    margin-top: 20px;
    text-align: right;
}

@media (max-width: 768px) {
    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .search-form .el-form-item {
        width: 100%;
        margin-right: 0;
    }

    .table-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .chart-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}
</style>